import requests
import logging
from datetime import datetime

class AlertManager:
    def __init__(self, webhook="", retry=3, timeout=5):
        self.webhook = webhook
        self.retry = retry
        self.timeout = timeout

    def format_alert_content(self, instance_name, host, status, check_time, is_normal=False):
        """格式化告警内容"""
        if is_normal:
            return f"""# 数据库服务状态正常 ✅
            >服务名称: <font color="info">{instance_name}</font>
            >运行状态: <font color="info">{status}</font>
            >检查时间: <font color="comment">{check_time}</font>"""
        else:
            return f"""# 数据库服务异常警报 ⚠️
            >服务名称: <font color="warning">{instance_name}</font>
            >服务地址：[{host}]()
            >运行状态: <font color="info">{status}</font>
            >检查时间: <font color="comment">{check_time}</font>"""

    def send_alert(self, content):
        """发送企业微信告警"""
        if not self.webhook:
            logging.error("警告：未配置企业微信参数，无法发送告警")
            return False

        for _ in range(self.retry):
            try:
                response = requests.post(
                    self.webhook,
                    json={
                        "msgtype": "markdown",
                        "markdown": {"content": content}
                    },
                    timeout=self.timeout
                )
                response.raise_for_status()
                return True
            except Exception as e:
                logging.error(f"企业微信通知失败: {str(e)}")
        return False

    def send_instance_alert(self, instance_name, host, status, is_normal=False):
        """发送实例状态告警"""
        check_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        content = self.format_alert_content(
            instance_name=instance_name,
            host=host,
            status=status,
            check_time=check_time,
            is_normal=is_normal
        )
        return self.send_alert(content)

    def format_full_status_report(self, all_instances_status):
        """格式化全量状态报告"""
        try:
            # 验证输入数据
            if not isinstance(all_instances_status, list):
                return "错误：实例状态数据格式不正确，应为列表格式"
                
            if not all_instances_status:
                return "当前没有实例状态数据可供显示"
            
            check_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            # 获取组名
            group_name = all_instances_status[0].get('group', '未分组')
            
            # 统计正常和异常的实例数量
            normal_count = sum(1 for status in all_instances_status if status.get('is_normal', False))
            failed_count = len(all_instances_status) - normal_count
            
            # 构建报告标题和摘要
            content = "# {} 组数据库状态报告 📊\n".format(group_name)
            content += ">检查时间: <font color=\"comment\">{}</font>\n".format(check_time)
            content += ">实例总数: <font color=\"info\">{}</font>\n".format(len(all_instances_status))
            content += ">正常实例: <font color=\"info\">{}</font>\n".format(normal_count)
            content += ">异常实例: <font color=\"warning\">{}</font>\n".format(failed_count)
            
            # 添加实例状态信息
            if normal_count > 0:
                content += ">\n>**正常运行实例:**\n"
                for instance in all_instances_status:
                    if instance.get('is_normal', False):
                        content += ">-<font color=\"info\">{}</font>@{}\n".format(
                            instance.get('name', 'Unknown'), 
                            instance.get('host', 'Unknown')
                        )
            
            if failed_count > 0:
                content += ">\n>**异常运行实例:**\n"
                for instance in all_instances_status:
                    if not instance.get('is_normal', False):
                        content += ">- <font color=\"warning\">{}</font> @ {}/{}: {}\n".format(
                            instance.get('name', 'Unknown'), 
                            instance.get('host', 'Unknown'),
                            instance.get('service', 'Unknown'), 
                            instance.get('status', 'Unknown')
                        )
            
            return content
        except Exception as e:
            error_msg = f"格式化状态报告时发生错误: {str(e)}"
            logging.error(error_msg)
            return f"# 状态报告生成失败\n>错误信息: {error_msg}"
    
    def send_full_status_report(self, all_instances_status):
        """发送全量状态报告"""
        content = self.format_full_status_report(all_instances_status)
        return self.send_alert(content)
              